<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品分类
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">

                    <el-select v-model="query.scopeType" placeholder="请选择" class="filter-item mr10">
                        <el-option
                                v-for="item in scopeTypeOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>

                    <el-button type="primary" class="filter-item" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" class="filter-item" icon="el-icon-plus" @click="handleAdd">新增</el-button>

            </div>
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column label="范围" align="center" >
                    <template slot-scope="scope">
                        <el-tag type="success">
                            {{selectDictLabel(scopeTypeOptions, scope.row.scopeType)}}
                        </el-tag>
                    </template>
                </el-table-column>


                <el-table-column label="图片" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-thumb"
                                :src="scope.row.url"
                                :preview-src-list="[scope.row.url]"
                        ></el-image>
                    </template>
                </el-table-column>

                <el-table-column prop="orderNum" label="排序"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.current"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="类型" prop="title" >
                    <el-select v-model="form.type" placeholder="请选择">
                        <el-option label="图片" value="1"></el-option>
                        <el-option label="视频" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图片" v-show="form.type == '1'">
                    <el-upload
                            ref="upload"
                            class="avatar-uploader"
                            action=""
                            :http-request="fileUpload"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="form.url" :src="form.url" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="视频" v-show="form.type == '2'">
                    <el-input v-model="form.url"></el-input>
                </el-form-item>
                <el-form-item label="范围">
                    <el-select v-model="form.scopeType" placeholder="请选择">
                        <el-option
                                v-for="item in scopeTypeOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="跳转路径">
                    <el-input v-model="form.jumpUrl"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <el-input v-model.number="form.orderNum"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { shopBannerPage,shopBannerSave,shopBannerUpdate,shopBannerDelete } from '../../../api/shop/shopBanner';

import { fileUpload } from '../../../api/uploadFile';

export default {
    name: 'shop-banner-list',
    data() {
        return {
            // 遮罩层
            loading: true,
            query: {
                scopeType: '',
                current: 1,
                size: 10
            },
            editVisible:false,
            form:{
                type:"1",
                url:"",
                scopeType:"1",
                jumpType:"1",
                jumpUrl:"",
                orderNum:0
            },
            scopeTypeOptions:[],
            tableData: [],
            pageTotal: 0,
            rules: {
                orderNum: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: 'number', message: '排序必须为数字值'}
                ]
            }
        };
    },
    created() {
        this.getDicts("shop_scope_type").then( async res => {
            let data = res.data;
            this.scopeTypeOptions = data;
            // 需要push
            this.defaultform = JSON.parse(JSON.stringify(this.form));
        });
        this.getData();
    },
    destroyed() {
        this.defaultform = null;
    },
    methods: {
        getData() {
            this.loading = true;
            shopBannerPage(this.query).then(res => {
                this.loading = false;
                this.tableData = res.data;
                this.pageTotal = res.count;
            });
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    shopBannerDelete(row.id).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`删除成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                })
                .catch(() => {});
        },
        handleAdd(){
            this.form = Object.assign({}, this.defaultform);
            this.editVisible = true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            })
        },
        handleEdit(index, row) {
            this.form.id = row.id;
            this.form.type = row.type;
            this.form.scopeType = row.scopeType;
            this.form.url = row.url;
            this.form.orderNum = row.orderNum;
            this.form.jumpUrl = row.jumpUrl;

            this.editVisible = true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            })
        },
        // 保存编辑
        saveEdit() {
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                if (this.form.id) {
                    shopBannerUpdate(this.form).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`修改成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                } else {
                    shopBannerSave(this.form).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`修改成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                }
            });
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        fileUpload(file){
            let _this = this;
            return fileUpload(file).then(res => {
                // 多图片上传，结果data里面是一个array
                // console.log(res.data[0]);
                _this.form.url = res.data[0]
                // _this.handleAvatarSuccess(res, file)
                _this.$refs.upload.clearFiles();//清空
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.filter-item {
    display: inline-block;
    vertical-align: middle;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.avatar-uploader  {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 148px;
    height: 148px;
    position: relative;
    overflow: hidden;
}
.avatar-uploader:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
}
.avatar {
    width: 148px;
    height: 148px;
    display: block;
}
</style>
